package com.yulebaby.callsenter.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.fourmob.datetimepicker.date.DatePickerDialog;
import com.yulebaby.callsenter.R;
import com.yulebaby.callsenter.bean.CallLogBean;
import com.yulebaby.callsenter.bean.CustomerBean;
import com.yulebaby.callsenter.bean.ResultBean;
import com.yulebaby.callsenter.database.manager.Dao;
import com.yulebaby.callsenter.event.EventFactory;
import com.yulebaby.callsenter.event.RefreshEvent;
import com.yulebaby.callsenter.event.ShowResultEvent;
import com.yulebaby.callsenter.global.App;
import com.yulebaby.callsenter.http.callback.HttpCallback;
import com.yulebaby.callsenter.task.LoginTask;
import com.yulebaby.callsenter.task.RequestTranProgressTask;
import com.yulebaby.callsenter.task.UploadCallLogTask;
import com.yulebaby.callsenter.ui.activity.LoginActivity;
import com.yulebaby.callsenter.ui.base.BaseFragment;
import com.yulebaby.callsenter.ui.view.PromptDialog;
import com.yulebaby.callsenter.utils.DateUtil;
import com.yulebaby.callsenter.utils.SPUtil;
import com.yulebaby.callsenter.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Author: Zhangbo
 * Time: 2017/1/18
 */
public class DailyFragment extends BaseFragment implements DatePickerDialog.OnDateSetListener {


    @BindView(R.id.iv_loginout)
    ImageView mIvLoginout;
    @BindView(R.id.iv_calendar)
    ImageView mIvCalendar;
    @BindView(R.id.pb_showProgress)
    ProgressBar mPbShowProgress;
    @BindView(R.id.btn_reload)
    Button mBtnReload;
    @BindView(R.id.fl_daily_container)
    FrameLayout mFlDailyContainer;

    private View mPagerError;
    private PromptDialog mDialog;

    public static final String YULEBABY_TAG = "yulebaby_daily";
    final Calendar calendar = Calendar.getInstance();
    final DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(this, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), true);


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View layout = inflater.inflate(R.layout.fragment_daily, container, false);
        mPagerError = layout.findViewById(R.id.layout_error);
        ButterKnife.bind(this, layout);
        showLoadingView();
        return layout;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDialog != null) {
            mDialog.dismiss(); //防止窗体泄漏
        }
        EventBus.getDefault().unregister(this);
    }

    private void requestData() {
        RequestTranProgressTask.doRequestCheckTrackTarget(mActivity, new HttpCallback<ResultBean>() {
            @Override
            public void onSuccess(ResultBean result) {
                switch (result.getSimple_data()) {
                    case "0":
                        loadRootFragment(R.id.fl_daily_container, StatisticalTargetFragment.newInstance());
                        break;
                    case "1":
                        loadRootFragment(R.id.fl_daily_container, DynamicDailyFragment.newInstance());
                        break;
                }
            }

            @Override
            public void onFailParam(String info) {
                super.onFailParam(info);
                showErrorView();
            }

            @Override
            public void onFail(String exception) {
                super.onFail(exception);
                showErrorView();
            }
        });
    }

    public static DailyFragment newInstance() {
        Bundle args = new Bundle();
        DailyFragment fragment = new DailyFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        if (savedInstanceState == null) {
//            requestData();
            loadRootFragment(R.id.fl_daily_container, DynamicDailyFragment.newInstance());
        }

    }


    @OnClick({R.id.iv_loginout, R.id.btn_reload, R.id.iv_calendar})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_loginout:
                showLogoutDialog();
                break;
            case R.id.btn_reload:
                showLoadingView();
                requestData();
                break;
            case R.id.iv_calendar:
                ToastUtil.showToast("静态日报");
                initDatePick();
                break;
        }
    }


    /**
     * 接受刷新信息的请求
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showSuccessView(ShowResultEvent event) {
        if (event != null) {
            if (event.getResultEvent() == ShowResultEvent.SuccessEvent) {
                hideView();
            } else if (event.getResultEvent() == ShowResultEvent.FailEvent) {
                showErrorView();
            }
        }
    }

    @Override
    public void onDateSet(DatePickerDialog datePickerDialog, int year, int month, int day) {
        String mth = (month + 1) > 9 ? String.valueOf(month + 1) : "0" + (month + 1);
        long visitTime = DateUtil.stringToLong(year + "-" + mth + "-" + day);
        long now = DateUtil.stringToLong(DateUtil.getCurrentDate());
        if (visitTime > now) {
            ToastUtil.showToast("日报时间不能大于当前时间");
        } else if (visitTime == now) {
            EventBus.getDefault().post(EventFactory.CreateQueryDailyEvent(""));
        } else {
            //查询静态日报
            EventBus.getDefault().post(EventFactory.CreateQueryDailyEvent(year + mth + day));
        }
    }


    /**
     * 接受刷新信息的请求
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshEvent(RefreshEvent event) {
        if (event != null) {
            if (event.getRefreshType() == RefreshEvent.refreshDailyData) {
                requestData();
            }
        }
    }

    /**
     * 日期选择
     */
    private void initDatePick() {
        datePickerDialog.setVibrate(true);
        datePickerDialog.setYearRange(2010, 2030);
        datePickerDialog.setCloseOnSingleTapDay(false);
        datePickerDialog.show(getChildFragmentManager(), YULEBABY_TAG);
    }

    public void showLoadingView() {
        hideView();
        mPbShowProgress.setVisibility(View.VISIBLE);
    }

    private void hideView() {
        mPbShowProgress.setVisibility(View.INVISIBLE);
        mPagerError.setVisibility(View.INVISIBLE);
    }

    public void showErrorView() {
        hideView();
        mPagerError.setVisibility(View.VISIBLE);
    }

    private void showLogoutDialog() {
        mDialog = new PromptDialog(mActivity, "请确认是否退出重新登录?", "确认", "点错了", new PromptDialog.DialogCallBack() {
            @Override
            public void onConfirm() {
                showLoading("正在退出...");
                LoginTask.doLogout(mActivity, new HttpCallback<ResultBean>() {
                    @Override
                    public void onSuccessResultNull() {
                        processResult();
                    }

                    @Override
                    public void onFailParam(String info) {
                        super.onFailParam(info);
                        dismissLoading();
                    }

                    @Override
                    public void onFail(String exception) {
                        super.onFail(exception);
                        dismissLoading();
                    }
                });
            }
        });
        mDialog.show();
    }

    /**
     * 上传记录,清理信息
     */
    private void processResult() {
        Observable.create(new Observable.OnSubscribe<List<CallLogBean>>() {
            @Override
            public void call(Subscriber<? super List<CallLogBean>> subscriber) {
                subscriber.onNext(Dao.getInstance().listUnloadFailAll());
            }
        }).debounce(500, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(callLogBeenList -> {
                    UploadCallLogTask.doUploadListFiles(callLogBeenList);
                    SPUtil.clear();  //清除登录信息
                    Dao.getInstance().deleteAllBean(CallLogBean.class);  //清除数据库保存的信息
                    Dao.getInstance().deleteAllBean(CustomerBean.class);
                    startActivity(new Intent(mActivity, LoginActivity.class));
                    dismissLoading();
                    mDialog.dismiss();
                    JPushInterface.setAliasAndTags(App.mContext, "", null, null); //取消极光的注册
                    mActivity.finish();
                    ToastUtil.showToast("退出成功");
                });
    }
}
